package com.wans.guli.order.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;

import javax.annotation.PostConstruct;

@Configuration
@Slf4j
public class RabbitMQConfirmConfig implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
        rabbitTemplate.setMandatory(true); // 设置 mandatory 保证 ReturnCallback 生效
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            log.info("消息成功发送到交换机，订单号: {}",
                    correlationData != null ? correlationData.getId() : "未知");
        } else {
            log.error("消息发送到交换机失败: {}, 原因: {}", correlationData, cause);
        }
    }

    @Override
    public void returnedMessage(@NonNull Message message, int replyCode, @NonNull String replyText,
                                @NonNull String exchange, @NonNull String routingKey) {
        log.error("消息从交换机路由到队列失败: exchange={}, route={}, replyCode={}, replyText={}, message={}",
                exchange, routingKey, replyCode, replyText, message);
    }
}
